import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;


public class User extends Thread{
	private Socket socket;
	private MrMonitor mon;
	private InputStream is;
	private OutputStream os;
	private Sender sender;
	
	public User(MrMonitor mon, Socket socket, Sender sender){
		this.mon = mon;
		this.socket = socket;
		this.sender = sender;
		try {
			is = socket.getInputStream();
			os = socket.getOutputStream();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	
	public void run() {
		try {
			while(true){
				int i;
				i = is.read();
				String message = "";
				while(i != -1){
					if(i != '\n'){
						message += (char) i;
					} else {
						if(message.length() < 2){
							sendMessage("ERRAWR!");
						} else if (message.substring(0, 2).compareTo("M:") == 0){
							mon.setMessage(message.substring(2));
						} else if(message.substring(0, 2).compareTo("E:") == 0){
							sendMessage(message.substring(2));
						} else if (message.substring(0, 2).compareTo("Q:") == 0){
							sender.removeUser(this);
							socket.close();
							return;
						} else {
							sendMessage("ERRAWR!");
						}
						message = "";
					}
					i = is.read();
				}
				socket.close();
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public void sendMessage(String message) {
		try {
			os.write((message + '\n').getBytes());
			os.flush();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
} 
